package io.gitee.hefren.hhregistry.cluster;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import io.gitee.hefren.hhregistry.conf.HhRegisterConfigProperties;
import io.gitee.hefren.hhregistry.service.impl.HhRegisterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtilsProperties;

import java.util.List;

/**
 * register cluster
 * @Date 2024/5/17
 * @Author lifei
 */
public class Cluster {
    private static final Logger log = LoggerFactory.getLogger(Cluster.class);


    private HhRegisterConfigProperties hhRegisterConfigProperties;

    private List<Server> serverList;

    private Server MYSELF;
    @Value("${server.port:8383}")
    private Integer port;
    private String host;

    public Cluster(HhRegisterConfigProperties hhRegisterConfigProperties) {
        this.hhRegisterConfigProperties = hhRegisterConfigProperties;
    }


    public void init() {
        // 获取host
        try (InetUtils inetUtils = new InetUtils(new InetUtilsProperties())){
            this.host = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
        }catch (Exception e) {
            this.host = "127.0.0.1";
        }
        this.MYSELF = new Server(Strings.lenientFormat("http://%s:%s", this.host, port), true, false, -1L);
        // 获取Server列表
        initServerList();
        // 1. 探活； 2. 选主； 3. 数据同步
        new HhregistryServerHealth(this).checkServerHealth();
    }

    private void initServerList() {
        List<Server> servers = Lists.newArrayList();
        for (String url : hhRegisterConfigProperties.getServerList()) {
            if (url.contains("localhost")) {
                url = url.replace("localhost", this.host);
            } else if (url.contains("127.0.0.1")) {
                url = url.replace("127.0.0.1", this.host);
            }
            if (url.equals(self().getUrl())) {
                servers.add(self());
            } else {
                Server server = new Server();
                server.setUrl(url);
                server.setLeader(false);
                server.setStatus(false);
                server.setVersion(-1L);
                servers.add(server);
            }
        }
        this.serverList = servers;
    }


    public Server self() {
        this.MYSELF.setVersion(HhRegisterService.VERSION.get());
        return this.MYSELF;
    }

    public Server leader() {
        return serverList.stream().filter(Server::getStatus).filter(Server::getLeader).findAny().orElse(null);
    }

    public List<Server> getServerList() {
        return serverList;
    }
}
